#!/bin/bash
clear
PRG="$0"
PRGDIR=`dirname "$PRG"`
[ -z "$UPDATE_HOME" ] && UPDATE_HOME=`cd "$PRGDIR" >/dev/null;pwd`
export UPDATE_HOME
# check java
export JAVA_HOME=./update/jre
export PATH=$JAVA_HOME/bin:$PATH
export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
#java -version
CLASSPATH=""
for i in `ls $UPDATE_HOME/update/lib/*.jar`
do
    CLASSPATH=$CLASSPATH:$i
done

function usage {
        echo -e "\033[1mSYNOPSIS:  \033[0m"
        echo "  update.sh [-i] [-h]"
        echo -e "\033[1mOPTIONS: \033[0m"
        echo "  -i    : Run program in the interactive mode"
        echo "  -s    : Stop zcm-update program"
        echo "  -r    : Run program in the override mode"
        echo "  -h    : Print usage"
        echo -e "\033[1mEXAMPLES: \033[0m"
        echo "    update.sh -i"
}

function stop {
        pid=`ps -ef|grep java|grep zcmUpdate|awk '{print $2}'`
        if [ "$pid" != "" ] ; then
            echo "killing $pid"
            kill -9 $pid
        fi
}
DEBUG=""
ARGS=""
OPTS="-Dzcm.update.port=8080 -Dzcm.update.sslPort=25811 -Dspring.config.location=./update/conf/application.properties -DAPP_NAME=zcmUpdate -Xmx1024m -Xms512m -classpath $CLASSPATH"
while [ "$1" != "" ]; do
        case $1 in
                -h )
            usage
                        exit 0
                        ;;
                -s )
            stop
                        exit 0
                        ;;
                -d )
                        shift
                        DEBUG="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005"
                        ;;
                -r )
                        shift
                        OPTS="$OPTS -Doverride.mode=true"
                        ;;
                -i )
                        shift
                        ARGS="interactive.enabled"
                        ;;
                * )
                        error "Unknow option:$1"
                        usage
                        exit 1
        esac
done

count=`ps -ef|grep java|grep zcmUpdate|wc -l`

# check if update tool already running
if [ $count -ge 1 ] ; then
   echo "ZCM update tool already running, exit"
   exit 1
fi

if [ -d "$UPDATE_HOME/update/log" ]; then
mkdir -p $UPDATE_HOME/update/backup
  TIMESTAMP=`date "+%Y%m%d%H%M%S"`
  mv  $UPDATE_HOME/update/log $UPDATE_HOME/update/backup/log$TIMESTAMP
fi
mkdir -p $UPDATE_HOME/update/log

if [ -n "$ARGS" ] ; then
    java $OPTS $DEBUG com.ztesoft.zsmart.zcm.version.update.App $ARGS
else
    nohup java $OPTS $DEBUG com.ztesoft.zsmart.zcm.version.update.App >> ./update/log/output.log 2>&1 &
fi